<template>
  <el-menu-item index="3" @click="dialogVisible = true" class="menu-item"> 报告路况 </el-menu-item>
  <el-dialog
    v-model="dialogVisible"
    title="报告路况"
    width="600"
    :before-close="handleClose"
    draggable
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-position="top">
      <el-form-item label="事件类型" prop="eventType">
        <el-select v-model="formData.eventType" placeholder="请选择事件类型">
          <el-option label="碰撞" value="碰撞" />
          <el-option label="刮擦" value="刮擦" />
          <el-option label="翻车" value="翻车" />
          <el-option label="碾压" value="碾压" />
          <el-option label="刮蹭" value="刮蹭" />
          <el-option label="失火" value="失火" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>
      <el-form-item label="事件位置" prop="eventAddress">
        <el-input v-model="formData.eventAddress" placeholder="请输入事件发生地址"></el-input>
      </el-form-item>
      <el-form-item label="建筑标志" prop="nearbyBuilding">
        <el-input v-model="formData.nearbyBuilding" placeholder="请输入附近地标建筑" />
      </el-form-item>
      <el-form-item label="发生时间" prop="occurrenceTime">
        <el-date-picker
          v-model="formData.occurrenceTime"
          type="datetime"
          placeholder="请选择发生时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="new Date()"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="事件描述" prop="eventDescription">
        <el-input
          v-model="formData.eventDescription"
          type="textarea"
          :rows="2"
          placeholder="请详细描述具体情况"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="现场照片">
        <el-alert
          title="请上传不超过3张图片，且每张图片大小不超过5MB"
          type="info"
          :closable="false"
        />
        <el-upload
          :file-list="fileList"
          list-type="picture-card"
          :limit="3"
          :on-exceed="handleExceed"
          :before-upload="beforeUpload"
          :on-change="handleUpload"
          :on-remove="handleRemove"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :disabled="isSubmitting">
        提交报告
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const dialogVisible = ref(false)
const formData = ref({
  eventType: '',
  eventAddress: '',
  nearbyBuilding: '',
  occurrenceTime: '',
  eventDescription: '',
  eventPhoto: '',
})
const formRef = ref(null)
const isSubmitting = ref(false)

// 表单验证规则
const formRules = reactive({
  eventType: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
  eventAddress: [{ required: true, message: '请填写事件发生地址', trigger: 'blur' }],
  occurrenceTime: [
    {
      required: true,
      validator: (_, value, callback) => {
        if (!value) return callback(new Error('请选择发生时间'))
        if (new Date(value) > new Date()) {
          callback(new Error('发生时间不能晚于当前时间'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
  ],
  eventDescription: [{ required: true, message: '请输入事件描述', trigger: 'blur' }],
})

// 监听对话框关闭状态
watch(
  () => dialogVisible.value,
  (newVal) => {
    if (!newVal) {
      formRef.value?.resetFields()
      formData.value.eventPhoto = ''
    }
  },
)

// 处理文件列表
const fileList = computed({
  get: () => {
    return formData.value.eventPhoto
      ? formData.value.eventPhoto.split(',').map((url) => ({ url }))
      : []
  },
  set: (newVal) => {
    formData.value.eventPhoto = newVal.map((file) => file.url).join(',')
  },
})

// 图片上传处理
const handleExceed = () => ElMessage.warning('最多上传3张照片')
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isImage) ElMessage.error('只能上传图片文件!')
  if (!isLt5M) ElMessage.error('图片大小不能超过5MB!')
  return isImage && isLt5M
}

// 转Base64后的图片上传处理
const handleUpload = async (uploadFile) => {
  const formData = new FormData()
  formData.append('file', uploadFile.raw)
  try {
    const response = await axios.post('/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    formData.value.eventPhoto = response.data.url // 存储返回的 URL
  } catch (error) {
    ElMessage.error('上传失败')
  }
}

// 图片移除处理
const handleRemove = (uploadFile) => {
  // 过滤掉被删除的图片
  const newPhotos = fileList.value
    .filter((file) => file.url !== uploadFile.url)
    .map((file) => file.url)
  formData.value.eventPhoto = newPhotos.join(',')
}

// 表单提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    isSubmitting.value = true

    // 构造请求数据
    const reportData = {
      reportByWho: route.query.username,
      eventType: formData.value.eventType,
      eventAddress: formData.value.eventAddress,
      nearbyBuilding: formData.value.nearbyBuilding,
      occurrenceTime: formData.value.occurrenceTime,
      eventDescription: formData.value.eventDescription,
      // eventPhoto: formData.value.eventPhoto,
      eventPhoto: `https://picsum.photos/id/${Math.floor(Math.random() * 300) + 1}/${Math.floor(Math.random() * 11) * 10 + 100}/${Math.floor(Math.random() * 11) * 10 + 100}`,
      auditStatus: 'pending', // 默认审核状态
    }

    const token = localStorage.getItem('token')
    const response = await axios.post(
      'http://localhost:3001/addReport',
      { reportObj: reportData },
      {
        headers: { Authorization: `Bearer ${token}` },
      },
    )

    if (response.status === 201) {
      ElMessage.success('报告提交成功！')
      dialogVisible.value = false
    }
  } catch (error) {
    console.error('提交失败:', error)
    let message = '报告提交失败'

    if (error.response) {
      message = error.response.data.error || message
      // 处理令牌失效
      if (error.response.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        router.push('/login')
      }
    }
    ElMessage.error(message)
  } finally {
    isSubmitting.value = false
  }
}

// 对话框关闭处理
const handleCancel = () => {
  ElMessageBox.confirm('确定要放弃当前编辑的内容吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      dialogVisible.value = false
    })
    .catch(() => {})
}

const handleClose = (done) => {
  ElMessageBox.confirm('确定要放弃当前编辑的内容吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      done()
    })
    .catch(() => {})
}
</script>

<style lang="scss" scoped>
:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-top: 15px;
}

:deep(.el-button) {
  &[disabled] {
    cursor: wait !important;
  }
}
</style>
